package us.icitap.commandcenter.ui.configuration;

import java.util.List;

import org.vaadin.dialogs.ConfirmDialog;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;

import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.event.Action;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Table;
import com.vaadin.ui.Button.ClickEvent;

import us.icitap.commandcenter.CommandCenterUI;
import us.icitap.commandcenter.business.Result;
import us.icitap.commandcenter.business.ejb.persistence.CallReason;
import us.icitap.commandcenter.business.ejb.persistence.CommandCenter;
import us.icitap.commandcenter.business.ejb.persistence.Dispatcher;
import us.icitap.commandcenter.ui.custom.ConfirmDialogAction;
import us.icitap.commandcenter.ui.custom.CustConfirmDialog;
import us.icitap.commandcenter.ui.custom.CustSaveButton;
import us.icitap.commandcenter.ui.custom.CustTable;
import us.icitap.commandcenter.ui.custom.CustTextField;
import us.icitap.commandcenter.ui.custom.CustVerticalLayout;
import us.icitap.commandcenter.ui.custom.StatusColumnGenerator;
import us.icitap.commandcenter.utils.HandleNotification;

public class DispatcherConfigLayout extends CustVerticalLayout {

	
	private final BeanItemContainer<CommandCenter> ccBeans = new BeanItemContainer<CommandCenter>(CommandCenter.class);
	private final BeanItemContainer<Dispatcher> dispatcherBeans = new BeanItemContainer<Dispatcher>(Dispatcher.class);
	
	
	private final CustTable ccTable = new CustTable(null, ccBeans);
	private final CustTable dispatcherTable = new CustTable(null, dispatcherBeans);
	
	private final CustTextField dispatcherTextField = new CustTextField("Shperndares i ri");
	
	private final CustSaveButton saveButton = new CustSaveButton("SHTO");
	
	
	static final Action ACTION_ACTIVE = new Action("Bej AKTIVE");
    static final Action ACTION_UNACTIVE = new Action("Bej JO-AKTIVE");
	
	
	public DispatcherConfigLayout() {
		this.addComponent(this.ccTable);
		
		this.addComponent(this.dispatcherTable);
		
		
		ccTable.setCaption("Sallat Operative");
		ccTable.setVisibleColumns(new Object[]{"id","name","status"});
		ccTable.setColumnHeaders(new String[]{"id","EMRI", "STATUSI"});
		ccTable.setColumnWidth("id", 50);
		ccTable.setColumnWidth("name", 450);
		ccTable.setColumnWidth("status", 50);
		ccTable.addGeneratedColumn("status", new StatusColumnGenerator());
		
		dispatcherTable.setCaption("Shperndaresit");
		dispatcherTable.setVisibleColumns(new Object[]{"id", "name", "status"});
		dispatcherTable.setColumnHeaders(new String[]{"ID", "EMRI", "STATUSI"});
		dispatcherTable.setColumnWidth("id", 50);
		dispatcherTable.setColumnWidth("name", 350);
		dispatcherTable.setColumnWidth("status", 100);
		
		dispatcherTable.setWidth("550px");
		dispatcherTable.setPageLength(6);
		dispatcherTable.addGeneratedColumn("status", new StatusColumnGenerator());
		
		ccTable.setImmediate(true);
		ccTable.setSelectable(true);
		ccTable.addValueChangeListener(new ValueChangeListener() {
			
			@Override
			public void valueChange(ValueChangeEvent event) {
			
				if(!saveButton.isEnabled()) saveButton.setEnabled(true);
				final Object value = event.getProperty().getValue();
				 
				if(value == null) return;
				CommandCenter cc = (CommandCenter)value;
				  
				dispatcherBeans.removeAllItems();
				dispatcherBeans.addAll(cc.getDispatcherList());
 
				
			}
		});
		
		
		
		
		Result<List<CommandCenter>> result = CommandCenterUI.persistenceBean.getCommandCenters();
		if(result.isSucceeded()){
			ccBeans.removeAllItems();
			ccBeans.addAll(result.getObject());
			
			
		}
		else
			HandleNotification.showErrorOnScreen(result.getMessage());
		
		
		
		dispatcherTextField.setWidth("400px");
		FormLayout fl = new FormLayout();
		fl.addComponent(dispatcherTextField);
		HorizontalLayout hl = new HorizontalLayout();
		hl.addComponent(fl);
		hl.addComponent(saveButton);
		saveButton.setEnabled(false);
		hl.setComponentAlignment(saveButton, Alignment.MIDDLE_RIGHT);
		this.addComponent(hl);
		
		this.saveButton.addClickListener(new ClickListener() {
			
			@Override
			public void buttonClick(ClickEvent event) {
				CustConfirmDialog.show(getAddConfirmation, getUI(), "Jeni i sigurte qe doni ta ruani");
				
			}
		});
		
		
		
		dispatcherTable.addActionHandler(new Action.Handler() {
            public Action[] getActions(Object target, Object sender) {
               if(target == null) return null;
               Dispatcher dis = (Dispatcher)target;
               if(dis.isStatus())
            	   return new Action[]{ACTION_UNACTIVE};
               else
            	   return new Action[]{ACTION_ACTIVE};
            }
            
            public void handleAction(Action action, Object sender, Object target) {
            	Dispatcher dis = (Dispatcher) target;
            	if (ACTION_ACTIVE == action) {
            		dis.setStatus(true);
                    Result<Dispatcher> result  = CommandCenterUI.persistenceBean.saveEntity(dis);
                    if(result.isSucceeded())
                    	dispatcherTable.refreshRowCache();
                    else
                    	HandleNotification.showErrorOnScreen(result.getMessage());
                }
                else if (ACTION_UNACTIVE == action) {
                    dis.setStatus(false);
                    Result<Dispatcher> result  = CommandCenterUI.persistenceBean.saveEntity(dis);
                    if(result.isSucceeded())
                    	dispatcherTable.refreshRowCache();
                    else
                    	HandleNotification.showErrorOnScreen(result.getMessage());
                }

        }});
		
	}
	
	
	private void refreshTable(){
		if(ccTable.getValue() == null){
			dispatcherTable.removeAllItems();
			return;
		}
		
		Result<List<Dispatcher>> result =  CommandCenterUI.persistenceBean.getDispatchers((CommandCenter)ccTable.getValue());
		
		if(result.isSucceeded()){
			dispatcherTable.removeAllItems();
			dispatcherBeans.addAll(result.getObject());
		}
	}
	private final ConfirmDialogAction getAddConfirmation = new ConfirmDialogAction() {
		
		@Override
		public void actYes() {
			if(dispatcherTextField.getValue() != null && !"".equals(dispatcherTextField.getValue().toString().trim())){
				Dispatcher dispatcher = new Dispatcher();
				dispatcher.setName(dispatcherTextField.getValue().toString().toUpperCase());
				dispatcher.setCommandCenter((CommandCenter)ccTable.getValue());
				
				Result<Dispatcher> result = CommandCenterUI.persistenceBean.saveEntity(dispatcher);
				if(result.isSucceeded()){
					System.out.println("Ruajtja OK");
					refreshTable();
				}
				else
					HandleNotification.showErrorOnScreen(result.getMessage());
				
			}
			else
				HandleNotification.showWarningOnScreen("Teksti tek shperndaresi eshte bosh");
			
			
		}
		
		@Override
		public void actNO() {
			// TODO Auto-generated method stub
			
		}
	};
	
	
}
